package com.banyou.banyou.order;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.banyou.banyou.MainApplication;
import com.banyou.banyou.R;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.bean.order.CreateOrderBean;
import com.banyou.banyou.bean.order.OrderInfo;
import com.banyou.banyou.customviews.RadioGroupEx;
import com.banyou.banyou.order.agreement.AgreementActivity;
import com.banyou.banyou.order.pay.PayActivity;
import com.banyou.banyou.util.GlideUtil;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;
import com.socks.library.KLog;
import com.squareup.timessquare.CalendarPickerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.NumberPicker;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：下单类
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class DoOdrderActivity extends BaseActivity<DoOdrderPresenter> implements DoOdrderContract.View {

    @BindView(R.id.back_btn)
    ImageView mBackBtn;
    @BindView(R.id.title_bar)
    RelativeLayout mTitleBar;
    @BindView(R.id.main_img)
    ImageView mMainImg;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.sex)
    TextView mSex;
    @BindView(R.id.star_content)
    LinearLayout mStarContent;
    @BindView(R.id.num_btn)
    Button mNumBtn;
    @BindView(R.id.date_btn)
    Button mDateBtn;
    @BindView(R.id.time_content)
    RadioGroupEx mTimeContent;
    @BindView(R.id.edit_other)
    EditText mEditOther;
    @BindView(R.id.main_btn)
    Button mMainBtn;
    @BindView(R.id.agreement_checkbox)
    CheckBox mAgreementCheckbox;
    @BindView(R.id.agreement_text)
    TextView mAgreementText;
    @BindView(R.id.insurance_text)
    TextView mInsuranceText;
    @BindView(R.id.age)
    TextView mAge;
    @BindView(R.id.short_msg)
    TextView mShortMsg;
    @BindView(R.id.insurance_checkbox)
    CheckBox mInsuranceCheckbox;

    private AlertDialog mDateDialog, mOrderDialog, mInsuranceDialog;
    private long mDataTime = 86400000;
    private ArrayList<String> mSelectedDays = new ArrayList<>();
    private int mManNum, mDateNum;
    private OrderInfo mOrderInfo = new OrderInfo();//订单信息
    private Bundle mBundle;
    private double mReward;
    private double mInsurancePrace,mInsuranceSinglePrice=10;

    @Override
    protected DoOdrderPresenter initPresenter() {
        return new DoOdrderPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_do_order;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new DoOdrderModel());
        ButterKnife.bind(this);
        mBundle = getIntent().getBundleExtra("bundle");
        mReward=getIntent().getDoubleExtra("reward",0);
        initDate();//初始化显示
    }

    /**
     * 初始化日期显示
     */
    private void initDate() {
        Intent intent = getIntent();
        ArrayList<String> list = intent.getStringArrayListExtra("list");
        if (list != null && list.size() != 0) {
            mSelectedDays.addAll(list);
            TextView textView = new TextView(DoOdrderActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textView.setLayoutParams(params);
            textView.setText("你选择的预约日期：");
            mTimeContent.addView(textView);
            for (int i = 0; i < mSelectedDays.size(); i++) {
                View view = (LayoutInflater.from(DoOdrderActivity.this).inflate(R.layout.date_btn, null));
                TextView text = (TextView) view.findViewById(R.id.date_text);
                text.setText(mSelectedDays.get(i));
                mTimeContent.addView(view);
            }
            mDateBtn.setText("重新选择日期");
        }
        mName.setText("姓名：" + mBundle.getString("name"));
        if (mBundle.getString("sex").equals("M")) {
            mSex.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.boy), null);
        } else {
            mSex.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.girl), null);
        }
        mShortMsg.setText(mBundle.getString("shortMsg"));
        mAge.setText("年龄：" + mBundle.getString("age"));
        String sex = mBundle.getString("sex");
        if(sex.equals("M")) {
            mSex.setText("性别：男");
        }else{
            mSex.setText("性别：女");
        }
        mStarContent.removeAllViews();
        for (int i = 0; i < mBundle.getInt("level"); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            imageView.setImageResource(R.drawable.star);
            mStarContent.addView(imageView);
        }
        GlideUtil.circleLocalLoad(this, mBundle.getString("image"), mMainImg);

    }

    @Override
    protected String pageName() {
        return "下单页";
    }

    @OnClick({R.id.back_btn, R.id.num_btn, R.id.date_btn, R.id.main_btn, R.id.agreement_text, R.id.insurance_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                this.finish();
                break;
            case R.id.num_btn:
                showNumDialog();//显示数字选择dialog
                break;
            case R.id.date_btn:
                showDateDialog();//显示日期选择Dialog
                break;
            case R.id.main_btn:
                showOrderDialog();//显示最终确认订单的Dialog
                break;
            case R.id.agreement_text://进入协议页面
                Intent intent = new Intent(this, AgreementActivity.class);
                startActivity(intent);
                break;
            case R.id.insurance_text://显示保险明细
                showInsuranceDialog();
                break;
        }
    }

    /**
     * 显示保险费用明细Dialog
     */
    private void showInsuranceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.insurance_dialog, null);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mInsuranceHolder=new InsuranceViewHolder(view);
        mInsuranceHolder.mDayNum.setText("已选天数："+mSelectedDays.size()+"天");
        mInsuranceHolder.mManNum.setText("已选人数："+mManNum+"人");
        mInsurancePrace=mDateNum*mManNum*mInsuranceSinglePrice;
        mInsuranceHolder.mInsurancePrice.setText(mInsuranceSinglePrice+"￥/天");
        mInsuranceHolder.mInsuranceTotalPrice.setText(mInsurancePrace+"￥");
        builder.setTitle("保险明细")
                .setCancelable(true)
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mInsuranceDialog != null && mInsuranceDialog.isShowing()) {
                            mInsuranceDialog.dismiss();
                        }
                    }
                });
        mInsuranceDialog = builder.create();
        mInsuranceDialog.show();
    }

    private ViewHolder mOrderDialogHolder;
    private InsuranceViewHolder mInsuranceHolder;

    /**
     * 显示下单Dialog
     */
    private void showOrderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请确认你的订单");
        View view = LayoutInflater.from(this).inflate(R.layout.order_dialog, null);
        mOrderDialogHolder = new ViewHolder(view);
        mOrderDialogHolder.mName.setText("伴游姓名：" + mBundle.getString("name"));
        String s = "";
        for (int i = 0; i < mSelectedDays.size(); i++) {
            if (i == mSelectedDays.size() - 1) {
                s += mSelectedDays.get(i);
            } else {
                s += mSelectedDays.get(i) + ",";
            }
        }
        mOrderDialogHolder.mTime.setText("已选日期：" + s);
        mOrderDialogHolder.mManNum.setText("已选人数："+mManNum);
        mInsurancePrace=mDateNum*mManNum*mInsuranceSinglePrice;
        mOrderDialogHolder.mTotalPrice.setText((int)(mReward*mDateNum+mInsurancePrace)+"￥");
        builder.setView(view).setCancelable(true);
        mOrderDialog = builder.create();
        mOrderDialog.show();
        //设置Dialog显示
        mOrderDialogHolder.mOrderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOrder();
            }
        });

    }

    /**
     * 联网下单
     */
    private void onOrder() {
        String buffer = "";
        for (int i = 0; i < mSelectedDays.size(); i++) {
            if(mSelectedDays.size()-1==i){
                buffer+=mSelectedDays.get(i);
            }else {
                buffer += mSelectedDays.get(i) + ",";
            }
        }
        mOrderInfo.setOrderDates(buffer);
        mOrderInfo.setOrderDays(mSelectedDays.size());
        mOrderInfo.setOrderUserNum(mManNum);
        List<OrderInfo.SysOrderUserRelatsBean> list = new ArrayList<>();
        OrderInfo.SysOrderUserRelatsBean sysOrderUserRelatsBean = new OrderInfo.SysOrderUserRelatsBean();
        sysOrderUserRelatsBean.setRelUserId(getIntent().getIntExtra("userId",0));
        list.add(sysOrderUserRelatsBean);
        OrderInfo.SysUserInsuranceBean insuranceBean=new OrderInfo.SysUserInsuranceBean();
        mInsurancePrace=mDateNum*mManNum*mInsuranceSinglePrice;
        insuranceBean.setInsuranceId(120);
        //TODO 修改保险ID
        insuranceBean.setInsuranceBalance((int)mInsurancePrace);
        mOrderInfo.setSysOrderUserRelats(list);
        mOrderInfo.setSysUserInsurance(insuranceBean);
        mOrderInfo.setUserId(Integer.parseInt(getSharedPreference().getString("userId","")));
        KLog.a("userId="+getIntent().getIntExtra("userId",0));
        mOrderInfo.setTotalPrice((int)(mReward*mDateNum+mInsurancePrace));
        mOrderInfo.setRemarks(mEditOther.getText().toString());
        mPresenter.doOrder(JSON.toJSONString(mOrderInfo));


    }

    /**
     * 日期选择Dialog
     */
    private void showDateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Calendar nextYear = Calendar.getInstance();
        nextYear.add(Calendar.MONTH, 1);
        View view = LayoutInflater.from(this).inflate(R.layout.activity_info_dialog, null);
        final CalendarPickerView calendar = (CalendarPickerView) view.findViewById(R.id.calendar_view);
        Date today = new Date();

        calendar.init(today, nextYear.getTime()).inMode(CalendarPickerView.SelectionMode.MULTIPLE);
        //设定点击到不可选日期时，弹出的提示
        calendar.setOnInvalidDateSelectedListener(new CalendarPickerView.OnInvalidDateSelectedListener() {
            @Override
            public void onInvalidDateSelected(Date date) {
                Toast.makeText(MainApplication.getContext(), "请选择可选绿色的日期", Toast.LENGTH_SHORT).show();
            }
        });
        //设置一个确定按钮
        builder.setView(view)
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDateDialog.dismiss();
                    }
                });
        mDateDialog = builder.create();
        //Dialog窗口Dismiss的时候
        mDateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                List<Date> selectedDates = calendar.getSelectedDates();
                if (selectedDates.size() != 0) {
                    //在这里添加一行文字
                    TextView textView = new TextView(DoOdrderActivity.this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    textView.setLayoutParams(params);
                    textView.setText("你选择的预约日期：");
                    mTimeContent.addView(textView);
                }
                //循环已选择日期，平铺展示在界面上
                mSelectedDays.clear();
                for (int i = 0; i < selectedDates.size(); i++) {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
                    SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sdf.format(selectedDates.get(i));
                    View view = (LayoutInflater.from(DoOdrderActivity.this).inflate(R.layout.date_btn, null));
                    TextView textView = (TextView) view.findViewById(R.id.date_text);
                    textView.setText(format);
                    mSelectedDays.add(fullSdf.format(selectedDates.get(i)));
                    mTimeContent.addView(view);
                }
                mDateNum = mSelectedDays.size();//保险详情，天数
            }
        });
        //弹出dialog的时候，清空已选日期
        mDateDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                mTimeContent.removeAllViews();
            }
        });
        mDateDialog.show();
    }

    //人数选择监听
    NumberPicker.OnNumberPickListener mPickListener = new NumberPicker.OnNumberPickListener() {
        @Override
        public void onNumberPicked(int index, Number item) {
            int num = item.intValue();
            mNumBtn.setText("同行人数：" + num + "人");
            mManNum = item.intValue();//保险详情，人数
        }
    };

    /**
     * 显示人数选择Dialog
     */
    private void showNumDialog() {
        NumberPicker picker = new NumberPicker(this);
        picker.setItemWidth(200);
        picker.setCycleDisable(true);
        picker.setCanceledOnTouchOutside(true);
        picker.setOffset(5);//偏移量
        picker.setRange(1, 99, 1);//数字范围
        picker.setSelectedItem(3);
        picker.setLabel("人");
        picker.setCancelable(true);
        picker.setOnNumberPickListener(mPickListener);
        picker.show();
    }

    /**
     * 下单成功
     */
    @Override
    public void doOrderSuccess(CreateOrderBean bean) {
        ShowToast.showToast("下单成功");
        if(bean.getCustomerOrderId()!=0){
            Intent intent=new Intent(this, PayActivity.class);
            intent.putExtra("orderId",bean.getOrderId());
            intent.putExtra("price",(int)(mReward*mDateNum+mInsurancePrace));
            startActivity(intent);
        }else{
            KLog.a("没有订单号");
            ShowToast.showToast("系统出错");
        }
    }

    /**
     * 下单失败
     * @param e
     */
    @Override
    public void doOrderFail(Throwable e) {
        if(e instanceof ProgressSubscriber.ReturnCodeErrorException){
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        }else{
            ShowToast.showToast("下单失败");
        }
    }

    static class ViewHolder {
        @BindView(R.id.total_price)
        TextView mTotalPrice;
        @BindView(R.id.place)
        TextView mPlace;
        @BindView(R.id.name)
        TextView mName;
        @BindView(R.id.time)
        TextView mTime;
        @BindView(R.id.insurance)
        TextView mInsurance;
        @BindView(R.id.order_btn)
        Button mOrderBtn;
        @BindView(R.id.man_num)
        TextView mManNum;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class InsuranceViewHolder {
        @BindView(R.id.people_num)
        TextView mManNum;
        @BindView(R.id.day_num)
        TextView mDayNum;
        @BindView(R.id.insurance_type)
        TextView mInsuranceType;
        @BindView(R.id.insurance_price)
        TextView mInsurancePrice;
        @BindView(R.id.insurance_total_price)
        TextView mInsuranceTotalPrice;

        InsuranceViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
